package org.bees.cms.web.util.velocity.editer;

import java.io.Serializable;
import java.util.Map;

import net.sf.json.JSONObject;

import org.bees.cms.web.util.Beans;

public class ComboEditer extends AbstractMultipleEditer {
	private Integer size = 1; // 最多显示个数
	private Boolean multiple = false;

	@Override
	public void initialize(JSONObject json) throws Exception {
		super.initialize(json);
		size = json == null ? size : json.containsKey("size") ? json.getInt("size") : size;
		multiple = json == null ? multiple : json.containsKey("multiple") ? json.getBoolean("multiple") : multiple;
	}

	@Override
	public String edit(Serializable t) throws Exception {
		values = t == null ? values : Beans.getList(t, property);

		StringBuilder builder = new StringBuilder();
		builder.append("<select");
		builder.append(" id='" + id + "'");
		builder.append(" class='" + clazz + "'");
		builder.append(" style='" + style + "'");
		builder.append(" name='" + name + "'");
		builder.append(" size='" + size + "'");
		builder.append(multiple ? " multiple='multiple'" : "");
		builder.append(" validator='" + validator + "'");
		builder.append(">");

		for (Map.Entry<String, String> entry : map.entrySet()) {
			builder.append("<option");
			builder.append(" value='" + entry.getValue() + "'");
			if (values.contains(entry.getValue())) {
				builder.append(" ").append("selected='selected'");
			}
			builder.append(">");
			builder.append(entry.getKey());
			builder.append("</option>");
		}

		builder.append("</select>");

		return builder.toString();
	}

	@Override
	public void destroy() throws Exception {
		super.destroy();
		size = null;
	}

	public Integer getSize() {
		return size;
	}

	public void setSize(Integer size) {
		this.size = size;
	}

	public Boolean getMultiple() {
		return multiple;
	}

	public void setMultiple(Boolean multiple) {
		this.multiple = multiple;
	}

}
